class MachinesController < ApplicationController 
  before_filter :check_authentication, :except => [:show, :ping, :getPingMachines , :index, :listInfoMachine]
  
  require 'ping'  
  layout 'layout'
  
  # GET /machines
  # GET /machines.xml
  def index
    @machines = Machine.all(:order =>"ordre")
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @machines }
    end 
    

  end

  # GET /machines/1
  # GET /machines/1.xml
  def show
    @machine = Machine.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @machine }
    end
  end

  # GET /machines/new
  # GET /machines/new.xml
  def new
   
    @machine = Machine.new(:salle_id => params[:salle_id])
    @salles = Salle.all
    @salles.push(Salle.new(:id => 0, :nom_salle => '-Sans salle-'))
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @machine }
    end
  end

  # GET /machines/1/edit
  def edit
    @machine = Machine.find(params[:id])
    @salles = Salle.all
  end

  # POST /machines
  # POST /machines.xml
  def create
    if params[:machine][:salle_id] == ""
      params[:machine][:salle_id] = 0
    end 
    @machine = Machine.new(params[:machine])
    @machine.up_at = Time.new
    if request.xml_http_request?
      if @machine.save
        addTolog(current_user.id,"La machine " + @machine.nom_machine.to_s + " a été créée") 
        if (defined? params[:machine][:salle_id])
          @machines = Machine.find_all_by_salle_id(params[:machine][:salle_id])
        else
          @machines = Machine.all
        end
        render :update do |page|
          page.replace_html "liste_machines_"+@machine.salle_id.to_s, :partial => 'machines/listMachine', :locals => {:machines => @machines, :salle_id => @machine.salle_id.to_s}
          page.replace_html "notice_message", image_tag("accept.png", :title => "OK !",:alt =>"OK !", :height =>"16px", :width =>"16px" )+" Machine ajoutée avec succès"
          page << "gererNoticeMessage()"
          #page.insert_html :bottom, "liste_machines_"+@machine.salle_id.to_s, :partial => 'machines/listMachine', :locals => {:machines => @machines}
          #page.insert_html :bottom, "machines_sort_"+@machine.salle_id.to_s, :partial => 'machines/machine', :locals => {:machine => @machine, :salle_id => @machine.salle_id.to_s}
        end # end render
      else
        render :update do |page|
          page.replace_html "error_message", "Erreur ajout machine"
          page << "gererErrorMessage()"
        end #end render
      end #end machine save
     else
       respond_to do |format|
      if @machine.save
        addTolog(current_user.id,"La machine " + @machine.nom_machine.to_s + " a été crée") 
        flash[:notice] = 'La machine a été correctement crée.'
        format.html { redirect_to(@machine) }
        format.xml  { render :xml => @machine, :status => :created, :location => @machine }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @machine.errors, :status => :unprocessable_entity }
      end
     end  
    end
  end

  # PUT /machines/1
  # PUT /machines/1.xml
  def update
    if params[:machine][:salle_id] == ""
      params[:machine][:salle_id] = 0
    end 
    @machine = Machine.find(params[:id])

    respond_to do |format|
      if @machine.update_attributes(params[:machine])
        addTolog(current_user.id,"La machine " + @machine.nom_machine.to_s + " a été modifiée")
        flash[:notice] = 'La machine a été mise jour avec succès'
        format.html { redirect_to(@machine) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @machine.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /machines/1
  # DELETE /machines/1.xml
  def destroy
    @machine = Machine.find(params[:id])
    id_salle = @machine.salle_id
    @machine.destroy
    
    #On détruit les incidents associés à la machine
    @incidents = Incident.find_all_by_machine_id(params[:id])
    @incidents.each do |incident|
      incident.destroy      
    end
    addTolog(current_user.id,"Machine " + @machine.nom_machine.to_s + " supprimée")
    if request.xml_http_request?
       @machines = Machine.find_all_by_salle_id(@machine.salle_id, :order =>"ordre")
      render :update do |page|
        page.replace_html "tr_machine_#{params[:id]}", ""
        if id_salle > 0
          #page.replace_html "liste_machines_"+@machine.salle_id.to_s, ""
          #page.insert_html :bottom, "liste_machines_"+@machine.salle_id.to_s, :partial => 'machines/listMachine', :locals => {:machines => @machines}
          page.replace_html "tr_machine_#{@machine.id}", ""
          page << "$('tr_machine_"+@machine.id.to_s+"').setAttribute('id', '');"
          page.replace_html "notice_message", image_tag("accept.png", :title => "OK !",:alt =>"OK !", :height =>"16px", :width =>"16px" )+" Machine supprimée avec succès"
          page << "gererNoticeMessage()"
          #page << "$('notification').hide()"
        else
          page.replace_html "notice_message", image_tag("accept.png", :title => "OK !",:alt =>"OK !", :height =>"16px", :width =>"16px" )+" Machine supprimée avec succès"
          page << "gererNoticeMessage()"
          #page << "$('notification').hide()"
          #page.replace_html "liste_machine_sans_salle", "<h2>Machine(s) sans salle</h2>"
        end        
      end #end render
    else
      respond_to do |format|
        format.html { redirect_to(machines_url) }
        format.xml  { head :ok }
      end
    end
  end
  
  def changeMachine
    @machine = Machine.find(params[:machine_id])
    
    if @machine.salle_id > 0
      @nomSalleSrc = Salle.find(@machine.salle_id).nom_salle
    else 
      @nomSalleSrc = "Sans salle"
    end
    @salle_dest = Salle.find(params[:salle_id])
    
    if @machine.salle_id.to_i != params[:salle_id].to_i
      addTolog(current_user.id,"Changement salle : machine "+@machine.nom_machine.to_s + " : de "+@nomSalleSrc.to_s + " vers " +@salle_dest.nom_salle.to_s)
      @machine.update_attribute(:salle_id, params[:salle_id])
     @machines = Machine.find_all_by_salle_id(params[:salle_id], :order =>"ordre")
      
      render :update do |page|
        page.replace_html "tr_machine_#{@machine.id}", ""
        page << "$('tr_machine_"+@machine.id.to_s+"').setAttribute('id', '');"
        page.replace_html "liste_machines_"+@machine.salle_id.to_s, :partial => 'machines/listMachine', :locals => {:machines => @machines, :salle_id => params[:salle_id]}
        #page.insert_html :bottom, "liste_machines_"+@machine.salle_id.to_s, :partial => 'machines/listMachine', :locals => {:machines => @machines}
        #page.insert_html :bottom, "machines_sort_"+params[:salle_id].to_s, :partial => 'machines/machine', :locals => {:machine => @machine, :salle_id => params[:salle_id]}
        page.replace_html "notice_message", image_tag("accept.png", :title => "OK !",:alt =>"OK !", :height =>"16px", :width =>"16px" )+" Le changement de salle a été réalisé avec succès"
        page << "gererNoticeMessage()"
      end
    else
      render :nothing => true   
    end  
     
  end
  
  def changeMachineSansSalle
    @machine = Machine.find(params[:machine_id])
    @salle_src = Salle.find(@machine.salle_id)
    @machine.update_attribute(:salle_id, '0')
    
    @machines = Machine.find_all_by_salle_id(0, :order =>"ordre")    
    
    addTolog(current_user.id,"Changement salle : machine "+@machine.nom_machine.to_s + " : de "+@salle_src.nom_salle.to_s + " vers Sans salle ")
    
    render :update do |page|
      page.replace_html "tr_machine_#{@machine.id}", ""
      page << "$('tr_machine_"+@machine.id.to_s+"').setAttribute('id', '');"
      page.replace_html "liste_machine_sans_salle", "<h2>Machine(s) sans salle</h2>"
      page.insert_html :bottom, "liste_machine_sans_salle", :partial => 'machines/listMachine', :locals => {:machines => @machines, :salle_id => params[:salle_id]}
      #page.insert_html :bottom, "machines_sort_"+params[:salle_id].to_s, :partial => 'machines/machine', :locals => {:machine => @machine, :salle_id => params[:salle_id]}
      page.replace_html "notice_message", image_tag("accept.png", :title => "OK !",:alt =>"OK !", :height =>"16px", :width =>"16px" )+" Le changement de salle a été réalisé avec succès"
      page << "gererNoticeMessage()"
    end   
    
  end
  
  def ping
    
    @machine = Machine.find(params[:id])    
    if Ping.pingecho(params[:adresse_ip], 5, "echo") || Ping.pingecho(params[:adresse_ip], 5, 80) 
      @machine.update_attribute(:ping, 1)
      render :update do |page|
        page << "$('result_ping_machine_ok_"+params[:id].to_s+"').show();$('result_ping_machine_nok_"+params[:id].to_s+"').hide();"        
      end
      Incident.gererIncidentPing(params[:id], true) 
    else
      @machine.update_attribute(:ping, 0)
      render :update do |page|
         page << "$('result_ping_machine_ok_"+params[:id].to_s+"').hide();$('result_ping_machine_nok_"+params[:id].to_s+"').show();"
      end
      Incident.gererIncidentPing(params[:id], false)   
    end
    @machine.save
    addTolog(current_user.id,"Ping machine "+@machine.nom_machine.to_s)    
  end
  
  def getPingMachines
  @machines = Machine.all(:conditions => "salle_id > 0")
    render :update do |page|
      @machines.each do |machine|          
        if machine.ping == 1
          page << "if(($('result_ping_machine_ok_"+machine.id.to_s+"') != null && $('result_ping_machine_nok_"+machine.id.to_s+"') != null) || ($('result_ping_machine_ok_"+machine.id.to_s+"') != '' && $('result_ping_machine_nok_"+machine.id.to_s+"') != '')){$('result_ping_machine_ok_"+machine.id.to_s+"').show();$('result_ping_machine_nok_"+machine.id.to_s+"').hide();}"      
        else
          page << "if(($('result_ping_machine_ok_"+machine.id.to_s+"') != null && $('result_ping_machine_nok_"+machine.id.to_s+"') != null) || $('result_ping_machine_ok_"+machine.id.to_s+"') != '' && $('result_ping_machine_nok_"+machine.id.to_s+"') != ''){$('result_ping_machine_ok_"+machine.id.to_s+"').hide();$('result_ping_machine_nok_"+machine.id.to_s+"').show();}"
        end
        if Incident.getIncidentByMachine(machine.id)
          page.replace_html "accident_machine_"+machine.id.to_s, link_to(image_tag('warning.png', :title => "Il y a un ou plusieurs accident(s) sur cette machine",:alt =>"incident", :height =>"16px", :width =>"16px" ), :controller => :incidents, :action => 'showByMachine', :id => machine.id )
        end    
    end
  end
  end
      
  def sort
    @salle = Salle.find(params[:salle_id])
    salle_id = params[:salle_id]
    params["machines_sort_"+salle_id.to_s].each_with_index do |id, index|
      Machine.update_all(['ordre=?', index+1], ['id=?', id])
    end
    addTolog(current_user.id,"Trie des machines sur la salle : "+@salle.nom_salle.to_s)
    render :nothing => true
  end
  
  def listInfoMachine
    @machine = Machine.find(params[:id_machine])
    render(:partial => 'listInfoMachine', :locals => { :machine => @machine})
  end
  
  def agent
    diskfailure = 3
    ramfailure = 100
    cpufailure = 100
    uptimefailure = 600
    @machines = Machine.all
    #boucle sur chaques machines
    @machines.each do |machine| 
      #random des différentes valeurs
      rand_ram_usage = rand(90) + 11
      rand_cpu_usage = rand(100) + 1
      choixOS = rand(5)+ 1
      rand_ram_total = (rand(8) + 1) * 512
      rand_disk_total =(rand(100)+1)*10
      rand_pileouface1 = rand(4)
      rand_pileouface2 = rand(2)
      rand_disk_usage =(rand(8)+1)
  
          
      #dans le cas ou aucun OS est choisi (null dans la table) on choisi un OS au hasard
      if machine.os == nil
        if choixOS == 1
          machineos = "Windows 7"
        elsif choixOS == 2
            machineos = "Windows XP"
        elsif choixOS == 3
              machineos = "Linux"
        elsif choixOS == 4
                machineos = "Mac OS"
        else
                machineos ="Inconnu"
        end
        #on update le champ OS + les champs de bases de la machine qui ne bougerons plus par la suite
        machine.update_attributes(:os => machineos,:ram_total => rand_ram_total,:disk_total => rand_disk_total, :disk_usage => 0)
        puts "mise a jour agent ok pour "+machine.nom_machine.to_s
      end

     
        
       if rand_pileouface1 == 1 or rand_pileouface1 == 2 or rand_pileouface1 == 3
          if rand_pileouface2 == 1
            if (machine.disk_usage + rand_disk_usage) <= machine.disk_total
                machine.disk_usage = machine.disk_usage + rand_disk_usage
            end
          else
            if (machine.disk_usage - rand_disk_usage)  > 0
              machine.disk_usage = machine.disk_usage - rand_disk_usage
            end
          end
          
          timenow = Time.new 

          if rand_cpu_usage >= cpufailure
            inc = Incident.new(:id => "", :date_detection => timenow, :machine_id => machine.id, :type_incident_id => 4)
            inc.save
            Incident.sendmail(machine.nom_machine,"alerte cpu")
          end
          if machine.disk_total - machine.disk_usage < diskfailure
            inc = Incident.new(:id => "", :date_detection => timenow, :machine_id => machine.id, :type_incident_id => 2)
             inc.save
             Incident.sendmail(machine.nom_machine,"alerte disque")
          end
          if rand_ram_usage >= ramfailure
            inc = Incident.new(:id => "", :date_detection => timenow, :machine_id => machine.id, :type_incident_id => 1)
             inc.save
             Incident.sendmail(machine.nom_machine,"alerte ram")
            
          end
          if ( timenow - machine.up_at) > uptimefailure
            inc = Incident.new(:id => "", :date_detection => timenow, :machine_id => machine.id, :type_incident_id => 5)
            inc.save 
            Incident.sendmail(machine.nom_machine,"agent non fonctionnel")
            
          else
            Incident.resolve_inc(machine.id,5)           
          end
          machine.update_attributes(:ram_usage => rand_ram_usage,:cpu_usage => rand_cpu_usage,:disk_usage => machine.disk_usage,:up_at=>timenow)
          
       end#End if
    
     end#End each
  
    end#end self 
  end

